# -*- coding: utf-8 -*-
# @Date    : 2024/2/3
# @Author  : zouy
# @Email: 874112501@qq.com
import json
import os
import random
import re
import time

import requests
from loguru import logger

from utils.click_crack import ClickCrack

DIR_PATH = os.path.dirname(os.path.abspath(__file__))


def get_now():
    return str(int(time.time() * 1000))


def call_back_param():
    return "geetest_" + get_now()


def get_jsonp(text):
    jsonp_str = re.search(r"\((.*)\)", text, re.S).group(1)
    return json.loads(jsonp_str)


def download_img(file_name, *, url):
    """下载验证码图片"""
    resp = requests.get(url, headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"})
    pic_dir = os.path.join(DIR_PATH, 'pic')
    if not os.path.exists(pic_dir):
        os.mkdir(pic_dir)
    path = os.path.join(pic_dir, file_name)
    with open(path, mode="wb") as f:
        f.write(resp.content)
    return path


def __ease_out_expo(x):
    if x == 1:
        return 1
    else:
        return 1 - pow(2, -10 * x)


def get_track(distance):
    """生成轨迹"""
    if not isinstance(distance, int) or distance < 0:
        raise ValueError(f"distance类型必须是大于等于0的整数: distance: {distance}, type: {type(distance)}")
    # 初始化轨迹列表
    slide_track = [[random.randint(20, 60), random.randint(10, 40), 0]]
    # 共记录count次滑块位置信息
    count = 30 + int(distance / 2)
    # 初始化滑动时间
    # t = random.randint(50, 100)
    # 记录上一次滑动的距离
    _x = 0
    _y = 0
    for i in range(count):
        # 已滑动的横向距离
        x = round(__ease_out_expo(i / count) * distance)
        # 滑动过程消耗的时间
        t = random.randint(10, 20)
        if x == _x:
            continue
        slide_track.append([x - _x, _y, t])
        _x = x
    slide_track.append([0, 0, random.randint(200, 300)])
    return slide_track


def get_points(ques_path, click_imgs_path, action=False, user_click_crack=True):
    """获取点坐标"""
    # import importlib

    with open(os.path.join(DIR_PATH, click_imgs_path), 'rb') as f:
        captcha_image = f.read()
    logger.info(f'点击~~~【{len(ques_path)}】~~~个字符, 图片路径见：\n{["pic/" + os.path.basename(i) for i in ques_path]}')

    result = ClickCrack(bg=captcha_image).discern()
    return result


if __name__ == '__main__':
    # print(get_track(100))

    # static_url = 'https://static.geetest.com/'
    # ques_url = [
    #     "nerualpic/original_word_pic/jiangchengzhengjunti/8227e17a675f0f3dacf74e90c67cfbd7.png",
    #     "nerualpic/original_word_pic/jiangchengzhengjunti/49823b10035b99f66c69afecb35a2f93.png",
    #     "nerualpic/original_word_pic/jiangchengzhengjunti/48a4141d9c7e96a5f2aafb4c4ea6bc26.png"
    # ]
    # imgs_url = 'captcha_v4/993f682ed1/word/0af8d91d43/2022-04-21T09/ef7925007bd245859d872f2f620f9df1.jpg'
    # click_imgs_path = download_img('click-imgs.png', url=urljoin(static_url, imgs_url))
    # ques_path = []
    # for idx, que in enumerate(ques_url, start=1):
    #     slice_path = download_img(f'que-{idx}.png', url=urljoin(static_url, que))
    #     ques_path.append(slice_path)

    ques_path = ['pic/que-1.png', 'pic/que-2.png', 'pic/que-3.png']
    click_imgs_path = 'pic/click-imgs.png'
    points = get_points(ques_path, click_imgs_path)
    logger.info(f'识别坐标位置：{points}')  # [(127, 149), (153, 56)]  [[4128, 7325], [4993, 2933]]
